const Client = require('./base-client')
const { Transmission } = require('@ctrl/transmission')
const logger = require('../console-logger')

const TRANSMISSION_STATUS = {
    "-1": "All",
    "0": "Stopped",
    "1": "Check waiting",
    "2": "Checking",
    "3": "Download waiting",
    "4": "Downloading",
    "5": "Seed waiting",
    "6": "Seeding",
}
// transmission client
module.exports = class TransmissionClient extends Client{
    constructor(config) {
        super(config)
        this.clientType = 'transmission'
        this.instance = new Transmission({
            baseUrl: config.address,
            username: config.loginname,
            password: config.loginpwd,
        })
    }

    async getSetting() {
        const res = await this.instance.getSession()
        logger.debug('getSetting res: ', res)
        if (res.result === 'success')
            return {
                version: res.arguments.version,
                downloadDir: res.arguments['download-dir']
            }
        else
            return  {}
    }

    async addTorrent(torrent, options) {
        const addOptions = {
            'download-dir': options.downloadDir,
            paused: !options.startNow,
        }
        logger.debug('addTorrent req: ', torrent, addOptions)
        const res = await this.instance.addTorrent(torrent, addOptions)
        logger.debug('addTorrent res: ', res)
        // res :
        // {
        //     arguments: {
        //       'torrent-added': { // 'torrent-duplicate'
        //         hashString: '8bb7855f7b68e3a194f75f3e216c2e02bfd279eb',
        //         id: 13,
        //         name: 'Sentinelle.2021.FRENCH.1080p.NF.WEBRip.DDP5.1.x264-MRCS'
        //       }
        //     },
        //     result: 'success'
        // }
        if (res.result === 'success') {
            return true
            // return this.warpTorrent((res.arguments['torrent-added'] || res.arguments['torrent-duplicate']))
        } else {
            throw new Error(res.result)
        }
    } 
    
    async addMagnet(torrent, options) {
        const addOptions = {
            'download-dir': options.downloadDir,
            paused: !options.startNow,
        }
        logger.debug('addMagnet req: ', torrent, addOptions)
        const res = await this.instance.addMagnet(torrent, addOptions)
        logger.debug('addMagnet res: ', res)
        if (res.result === 'success') {
            return true
            // return this.warpTorrent((res.arguments['torrent-added'] || res.arguments['torrent-duplicate']))
        } else {
            throw new Error(res.result)
        }
    }
    async removeTorrent(ids, removeData) {
        logger.debug('removeTorrent req: ', ids, removeData)
        const res = await this.instance.removeTorrent(ids, removeData)
        logger.debug('removeTorrent res: ', res)
        return res.result === 'success' ? res.arguments : {}
    }
    async startTorrent(ids) {
        logger.debug('startTorrent req: ', ids)
        const res = await this.instance.resumeTorrent(ids)
        logger.debug('startTorrent res: ', res)
        return res.result === 'success' ? res.arguments : {}
    }
    async stopTorrent(ids) {
        logger.debug('stopTorrent req: ', ids)
        const res = await this.instance.pauseTorrent(ids)
        logger.debug('stopTorrent res: ', res)
        return res.result === 'success' ? res.arguments : {}
    }
    async verifyTorrent(ids) {
        logger.debug('verifyTorrent req: ', ids)
        const res = await this.instance.verifyTorrent(ids)
        logger.debug('verifyTorrent res: ', res)
        return res.result === 'success' ? res.arguments : {}
    }
    async setTorrentLocation(ids, location) {
        logger.debug('setTorrentLocation req: ', ids)
        const res = await this.instance.moveTorrent(ids, location)
        logger.debug('setTorrentLocation res: ', res)
        return res.result === 'success' ? res.arguments : {}
    }
    async listTorrents() {
        const res = await this.instance.listTorrents()
        const torrents = res.result === 'success' ? res.arguments.torrents : []
        return torrents.map(torrent => this.warpTorrent(torrent))
    }

    async getTorrent(id) {
        logger.debug('getTorrent id: ', id)
        const res = await this.instance.listTorrents(id)
        logger.debug('getTorrent res: ', res)
        const torrent = res.result === 'success' && res.arguments.torrents.length > 0 ? res.arguments.torrents[0] : {}
        return this.warpTorrent(torrent)
    }
    
    warpTorrent(torrent) {
        let warped = {}
        if (torrent) {
            warped.id = torrent.id
            warped.name = torrent.name
            warped.status = torrent.status !== undefined ? TRANSMISSION_STATUS[torrent.status] : ''
            warped.downloadDir = torrent.downloadDir
            warped.hashString = torrent.hashString
            warped.totalSize = torrent.totalSize
            warped.addedDate = torrent.addedDate
            warped.trackers = torrent.trackers
            warped.isPrivate = torrent.isPrivate
            warped.magnetLink = torrent.magnetLink
            // more
            warped.trackerStats = torrent.trackerStats
            warped.files = torrent.files
            warped.rateDownload = torrent.rateDownload
            warped.rateUpload = torrent.rateUpload
            warped.downloadedEver = torrent.downloadedEver
            warped.leftUntilDone = torrent.leftUntilDone
            warped.comment = torrent.comment
            warped.errorString = torrent.errorString
        }

        return warped
    }
}